#include "kv_store.h"

HashTable *g_hashTable;

// 哈希函数：将字符串 key 映射为哈希表索引
unsigned int hsh_function(const void *key, int capacity) 
{
    unsigned int seed = 131;  // 哈希种子（经验值，减少冲突）
    unsigned int hash = 0;

    char *buff = (char*)key;
    
    // 遍历字符串，计算哈希值
    while (*buff) {
        hash = hash * seed + (*buff++);
    }
    
    // 确保索引在 [0, capacity-1] 范围内
    return hash % capacity;
}

int compareChar(void* a, void* b)
{
    const char* str_a = (const char*)a;
    const char* str_b = (const char*)b;
    return strcmp(str_a, str_b); 
}

int kvs_hash_create()
{
    g_compare_hash = compareChar;
    g_hash_func = hsh_function;
    g_hashTable = hash_table_init(16);
	return 0;
}

int kvs_hash_free(HashTable *table)
{
    hash_table_clear(table);
	return 0;
}

char *kvs_hash_get(HashTable *table, char *key)
{
    HashNode *node = hash_get(table, key);
    if (node == NULL)
    {
        return NULL;
    }
    return (char*)node->value;
}

int kvs_hash_set(HashTable *table, char *key, char *value)
{
    return hash_insert(table,key,strlen(key) + 1,value,strlen(value) + 1);
}

int kvs_hash_mod(HashTable *table, char *key, char *value)
{
    int res = hash_modify(table,key,strlen(key) + 1,value,strlen(value) + 1);
    if (res == -1 || res == 1)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

int kvs_hash_del(HashTable *table, char *key)
{
    int res = hash_delete(table,key);
    if (res == -1 || res == 1)
    {
        return -1;
    }
    else
    {
        return 0;
    }
}

int kvs_hash_exist(HashTable *table, char *key)
{
    HashNode *node = hash_get(table, key);
    if (node == NULL)
    {
        return 0;
    }
    return 1;
}